<!-- 模板 -->
<template>
  <div id="CalendarSelector">
    <h2>{{isShow}}</h2>
    <div id="calendar-box" ref="calendarSelector" v-bind:class="{ show: isShow}">
      <div class="calendar-top border-b">
        <div class="left-btn tx-cyan" @click="submitCalendar">取消</div>
        <h3>时间选择器</h3>
        <div class="right-btn tx-cyan" @click="submitCalendar">确定</div>
      </div>
      <div class="calendar-content">
        <ul>
          <li>
            <ul class="c-week over-h">
              <li class="w-7 fl tx-orange">日</li>
              <li class="w-7 fl">一</li>
              <li class="w-7 fl">二</li>
              <li class="w-7 fl">三</li>
              <li class="w-7 fl">四</li>
              <li class="w-7 fl">五</li>
              <li class="w-7 fl tx-orange">六</li>
            </ul>
            <div class="calendar-month">
              <template v-for="item in calendarArr">
                <div class="c-month tx-gray border-b">{{item.monthTitle}}</div>
                <ul class="c-month_arr over-h border-b">
                  <li class="w-7 fl" v-for="day in item.month_arr">
                    <template v-if="day.day">
                      <div :title='day.dayTimestamp' @click="clickTimestamp($event)"  v-bind:class="{ disabled: day.disabled,selected:timestamp1<day.dayTimestamp&&timestamp2>day.dayTimestamp}">
                        {{day.day}}
                        <span class="message-start">开始</span><span class="message-end">结束</span>
                      </div>
                    </template>
                    <template v-else>
                    <div class="opa-0">&nbsp;</div>
                    </template>
                  </li>
                </ul>
              </template>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="cs-bg" ref="calendarSelectorBg" v-bind:class="{ show: isShow}"></div>
  </div>
</template>

<!-- js -->
<script>
//时间格式转化为时间戳  
function timeChangetype(stringTime){  
  var timestamp = Date.parse(new Date(stringTime));  
  return timestamp;  
}
//时间格式转化为标准时间 
function getTimestamp(dateStr){
  dateStr = dateStr.replace('年','-');
  dateStr = dateStr.replace('月','-');
  dateStr = dateStr.replace('日','-');
  return new Date(dateStr.replace(/-/g,'/')); 
}

// 时间戳转换成时间
function formatDate(str) {
  var now = new Date(str)
  var delimiter = '_'
  var year=now.getFullYear()
  var month=(now.getMonth()+1)
      month=month<10 ? '0' + month : month
  var date=now.getDate()
      date=date<10 ? '0' + date : date
  var hour=now.getHours()
  var hour=now.getHours()
  var minute=now.getMinutes()
  var second=now.getSeconds()
  return year+"-"+month+"-"+date
}

export default {
  name: 'calendar-selector',
  props: {
    'csOption': {
      type: Object,
      default: function () {
        return {timeStart:'2018-01-01', timeEnd:'2020-12-31', timeLength:0}
      }
    },
    'isShow': {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      timestamp: new Date().getTime(),
      nowYear: new Date().getFullYear(),
      nowMonth: new Date().getMonth(),
      nowWeek: new Date().getDay(),
      nowDay: new Date().getDate(),
      calendarArr: [],
      counter: 0,
      timestamp1: 0,
      timestamp2: 0
    }
  },
  mounted: function () {
    this.calendarArr = this.getCalendar()
  },
  methods: {
    getCalendar: function(){
      var day_ms = 24 * 60 * 60 * 1000
      var start_time = getTimestamp(this.csOption.timeStart)
      var start_time_timestamp = timeChangetype(start_time)
      var end_time = getTimestamp(this.csOption.timeEnd)
      var end_time_timestamp = timeChangetype(end_time)
      var length_time = this.csOption.timeLength
      var length_time_timestamp = length_time * day_ms
      var max_timestamp = end_time_timestamp + length_time_timestamp
      var length_time_total = (end_time_timestamp - start_time_timestamp)/day_ms+length_time
      var start_year = start_time.getFullYear()
      var start_month = start_time.getMonth()
      var start_day = start_time.getDate()
      var feb_bigDay = (start_year % 4 == 0) && (start_year % 100 != 0 || start_year % 400 == 0) ? 29 : 28
      var month_bigDay = [31, feb_bigDay, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
      var monthLength = 1
      var t = -start_day
      var defaultl = 36
      for (var m = 0; m < defaultl; m++) {
        var  j = start_month + m
        if(j > 11){
          j = 0
        }
        t += month_bigDay[j]
        if(t > length_time_total) {
          defaultl = m
        }
        monthLength = m + 1
      }
      var date_arr = []
      for (var i = 0; i < monthLength; i++) {
        date_arr[i] = {}
        date_arr[i].monthTitle = start_year + '年' + (start_month+1) +'月'
        var big_day = month_bigDay[start_month]
        var GMT08 = new Date(start_year, start_month, 1)
        var start_week = GMT08.getDay()
        var month_arr = []
        for (var k=0; k<start_week; k++) {
          month_arr.push({day: '', dayTimestamp: '', disabled: false})
        }
        for (var j = 0; j < big_day; j++) {
          var month_obj = {}
          var a = new Date(start_year, start_month, j + 1)
          var a_timestamp = timeChangetype(a)
          month_obj.day = a.getDate()
          month_obj.dayTimestamp = a_timestamp
          // console.log(a.getDate() >= start_day)
          if (a_timestamp < start_time_timestamp || a_timestamp > max_timestamp) {
            month_obj.disabled = true
          } else {
            month_obj.disabled = false
          }
          month_arr.push(month_obj)
        }
        // console.log(month_arr)
        date_arr[i].month_arr = month_arr
        start_month++
        if(start_month>11){
          start_year++
          start_month = 1
        }
      }
      return date_arr
    },
    clickTimestamp: function (ev) {
      var result = {}
      if (!ev.target.classList.contains('disabled')) {
        if (this.counter === 0) {
          this.timestamp1 = parseInt(ev.target.title)
          ev.target.id = 'firstClick'
          ev.target.classList.add('first-click')
          // 选择开始时间触发startChange事件
          this.counter = 1,
          result = {
            start_date: new Date(parseInt(ev.target.title))
          }
          this.$emit('selectError', result)
        } else {
          var firstClick = document.getElementById("firstClick")
          var lastClick = document.getElementById("lastClick")
          if (parseInt(ev.target.title) > this.timestamp1) {
            if(lastClick){
              this.timestamp2 = 0
              lastClick.classList.remove("last-click")
              lastClick.id = ''
            }
            // 获取选择天数
            var tval = parseInt(ev.target.title) - this.timestamp1
            var tday = tval / (24 * 60 * 60 * 1000) + 1
            if(tday<=this.csOption.timeLength){
              this.timestamp2 = parseInt(ev.target.title)
              ev.target.id = 'lastClick'
              ev.target.classList.add('last-click')
              // 选择结束时间触发endChange事件
              var result = {
                end_date: new Date(parseInt(ev.target.title))
              }
              this.$emit('endChange', result)
            }else{
              
              // 选择时间大于最长持续时间触发selectError事件
              result = {
                type: 'select_continue_long',
                date: new Date(parseInt(ev.target.title))
              }
              this.$emit('selectError', result)
            }
          } else {
            this.counter = 0
            if(firstClick){
              this.timestamp1 = 0
              firstClick.classList.remove("first-click")
              firstClick.id = ''
            }
            if(lastClick){
              this.timestamp2 = 0
              lastClick.classList.remove("last-click")
              lastClick.id = ''
            }
          }
        }        
      }else{
        result = {
          type: 'select_outtime',
          date: new Date(parseInt(ev.target.title))
        }
        this.$emit('selectError', result);
      }
    },
    cancelCalendar: function () {
      this.timestamp1 = 0
      this.timestamp2 = 0,
      this.$refs.calendarSelector.classList.remove("show")
      this.$refs.calendarSelectorBg.classList.remove("show")
      var firstClick = document.getElementById("firstClick")
      var lastClick = document.getElementById("lastClick")
      if(firstClick){
        firstClick.classList.remove("first-click")
        firstClick.id = ''
      }
      if(lastClick){
        lastClick.classList.remove("last-click")
        lastClick.id = ''
      }
    },
    submitCalendar: function () {
      var result = {}
      if (this.timestamp1 && this.timestamp2) {
        result = {
          code: 1,
          message: '操作成功',
          data:{srattime: new Date(this.timestamp1), endtime: new Date(this.timestamp2)}
        }
      } else {
        result = {
          code: 0,
          message: '操作失败',
          data:{}
        }
      }
      this.counter = 0
      this.$emit('sendCalendarResult', result)
      this.cancelCalendar()
    }
  }
}
</script>

<!-- style -->
<style scoped>
/*common css*/
ul,li,h3{
  padding: 0;
  margin: 0;
}
li{
  list-style: none;
}
.border-b{
  border-bottom:solid #ececec 1px;
}
.tx-orange{
  color: #c23047;
}
.tx-cyan{
  color: #00bcd2;
}
.tx-gray{
  color: #888;
}
.tx-yellow{
  color: #ed8000;
}
.w-7{
  width: 14.285714%;
}
.fl{
  float: left;
}
.over-h{
  overflow: hidden;
}
.opa-0{
  opacity: 0;
}
.dis-n{
  display: none;
}
/*my style*/
#calendar-box{
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100000;
  background-color: #fff;
  box-shadow: 0 0 10px #acacac;
  border-radius: .2em .2em 0 0;
  color: #131313;
  display: none;
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
}
#calendar-box.show{
   display: block;
}
.cs-bg{
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 99999;
  background-color: #000;
  opacity: .6;
  display: none;
}
.cs-bg.show{
  display: block;
}
.calendar-top{
  position: relative;
  height: 3em;
}
.calendar-top .left-btn{
  position: absolute;
  top: 0;
  left: 0;
  height: 3em;
  line-height: 3em;
  font-size: 1em;
  padding: 0 1em;
}
.calendar-top .right-btn{
  position: absolute;
  top: 0;
  right: 0;
  height: 3em;
  line-height: 3em;
  font-size: 1em;
  padding: 0 1em;
}
.calendar-top h3{
  line-height: 3em;
  font-size: 1em;
  color: #131313;
}
.c-week li{
  line-height: 2em;
  font-size: 0.9em;
  background-color: #eee;
}
.calendar-month{
  max-height: 25em;
  overflow-y: auto;
}
.c-month{
  font-size: 0.9em;
  line-height: 3em;
}
.c-month_arr li{
  line-height: 3.6em;
  font-size: 1.2em;
  position: relative;
}
.c-month_arr li label{
  display: block;
}
.c-month_arr li .disabled{
  color:#acacac;
}
.c-month_arr li .selected{
  background: #f2f2f2;
  color:#e74d4d;
}
.c-month_arr li span{
  display: none;
  position: absolute;
  bottom: 0;
  color: #fff;
  width: 100%;
  height: 20px;
  line-height: 20px;
}
.c-month_arr li .first-click{
  background-color: #e74d4d;
  color: #fff;
  border-radius: .4em 0 0 .4em;
}
.c-month_arr li .first-click span.message-start{
  display: block;
}
.c-month_arr li .last-click{
  background-color: #e74d4d;
  color: #fff;
  border-radius: 0 .4em .4em 0;
}
.c-month_arr li .last-click span.message-end{
  display: block;
}
.c-month_arr li:nth-child(7n){
  color:#ed8000;
}
.c-month_arr li:nth-child(7n-6){
  color:#ed8000;
}
</style>
